package czk.concrent.review.synControl;

/**
 * @Author:ChenZhangKun
 * @Date: 2020/7/22 23:53
 */
public class SynControl {
    public static void main(String[] args) {
        SynControlDemo synControl=new SynControlDemo(5,1);
        new Thread(()->{
            try {
                synControl.print("A",1,2);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }).start();
        new Thread(()->{
            try {
                synControl.print("B",2,3);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }).start();
        new Thread(()->{
            try {
                synControl.print("C",3,1);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }).start();
    }
}
class SynControlDemo{
    private int loopNum;
    private int i;

    public SynControlDemo(int loopNum,int i) {
        this.loopNum = loopNum;
        this.i=i;
    }
    public void print(String content,int waitFlag,int nextFlag) throws InterruptedException {
        for (int j = 0; j < loopNum; j++) {
            synchronized (this){
                // 避免虚假唤醒
                while(i!=waitFlag){
                    wait();
                }
                System.out.print(content);
                i=nextFlag;
                notifyAll();
            }
        }
    }
}
